package com.ttg.demo;

/**
 * @author zhenhao Ma
 * @date 2024/12/31 10:13
 */
import com.ttg.utils.sm.CryptoUtil;
import com.ttg.utils.sm2.SMUtil;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.util.encoders.Hex;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

/**
 * @author zhenhao Ma
 * @date 2024/12/31 9:38
 */
public class demo {

    public static void main(String[] args) throws Exception {
        /**
         * 对secret使用公钥进行SM2加密
         */

        KeyPair keyPair = SMUtil.generateKeyPair();

        PrivateKey aPrivate = keyPair.getPrivate();
        byte[] priBytes = SMUtil.privateKey(aPrivate.getEncoded());
        String priKey = CryptoUtil.bin2hex(priBytes);
        System.out.println("私钥：" + priKey);

        PublicKey aPublic = keyPair.getPublic();
        byte[] publicBytes = SMUtil.publicKey(aPublic.getEncoded());
        String pubKey = CryptoUtil.bin2hex(publicBytes);
        System.out.println("公钥：" + pubKey);

        String secret = "5621191118389481";
        byte[] resultData = SMUtil.sm2EncryptDataForPubKey(secret.getBytes("UTF-8"), "f50958afca754ecec9ad950a92ddd92e4487235066146e605286161a866c242d1a6b92df22109e0fcf183a63e5163d026479cccd2e213177ca85f9a001da45bc", false);
        String hex = null;
        if (resultData != null) {
            hex = CryptoUtil.bin2hex(resultData);
        }
        System.out.println("====加密后的secret= " + hex);
        byte[] bytes = SMUtil.sm2DecryptDataForPriKey(resultData, "13ba18d59b181443c391251e044a9ecd9876690e2acf9ebdfe8269377ea9d353", false);
        String hex1 = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("====解密后的secret= " + hex1);
    }

}
